#!/usr/bin/env python3

from flask import Flask, render_template, request, jsonify
import socket
import time
from datetime import datetime
import os

app = Flask(__name__)

# 基础配置
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False  # 简化JSON输出

def get_system_info():
    """获取系统基本信息"""
    try:
        import psutil
        cpu_usage = psutil.cpu_percent(interval=1)
        memory_usage = psutil.virtual_memory().percent
        disk_usage = psutil.disk_usage('/').percent
        boot_time = datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d %H:%M:%S')
    except ImportError:
        # 如果psutil不可用，使用模拟数据
        cpu_usage = 15.5
        memory_usage = 45.2
        disk_usage = 32.1
        boot_time = "2024-01-01 00:00:00"
    
    return {
        'hostname': socket.gethostname(),
        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'cpu_usage': cpu_usage,
        'memory_usage': memory_usage,
        'disk_usage': disk_usage,
        'boot_time': boot_time,
        'python_version': os.environ.get('PYTHON_VERSION', '未知')
    }

@app.route('/')
def index():
    """主页 - 显示服务器信息"""
    system_info = get_system_info()
    client_ip = request.remote_addr
    
    return render_template('index.html', 
                         system=system_info,
                         client_ip=client_ip)

@app.route('/health')
def health_check():
    """健康检查接口"""
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.now().isoformat(),
        'service': 'nginx-ha-test',
        'server': socket.gethostname()
    })

@app.route('/api/system')
def system_api():
    """系统信息API"""
    return jsonify(get_system_info())

@app.route('/api/visit')
def visit_api():
    """访问信息API"""
    return jsonify({
        'client_ip': request.remote_addr,
        'user_agent': request.headers.get('User-Agent', ''),
        'server': socket.gethostname(),
        'timestamp': datetime.now().isoformat()
    })

@app.route('/load-test')
def load_test():
    """负载测试页面"""
    # 简单的计算测试
    start_time = time.time()
    result = sum(i*i for i in range(5000))
    end_time = time.time()
    
    return jsonify({
        'status': 'load_test_completed',
        'calculation_result': result,
        'processing_time': round(end_time - start_time, 4),
        'server': socket.gethostname(),
        'timestamp': datetime.now().isoformat()
    })

@app.route('/info')
def info():
    """环境信息页面"""
    system_info = get_system_info()
    return f"""
    <h1>Nginx HA测试服务器信息</h1>
    <pre>
服务器主机名: {system_info['hostname']}
当前时间: {system_info['timestamp']}
CPU使用率: {system_info['cpu_usage']}%
内存使用率: {system_info['memory_usage']}%
磁盘使用率: {system_info['disk_usage']}%
启动时间: {system_info['boot_time']}
客户端IP: {request.remote_addr}
    </pre>
    <p><a href="/">返回主页</a></p>
    """

if __name__ == '__main__':
    print(" Nginx HA测试应用启动中...")
    print(" 访问地址: http://0.0.0.0:5000")
    print("  健康检查: http://0.0.0.0:5000/health")
    print(" 系统信息: http://0.0.0.0:5000/api/system")
    print(" 纯文本信息: http://0.0.0.0:5000/info")
    
    # 设置环境变量
    os.environ['PYTHON_VERSION'] = 'Python 3.x'
    
    app.run(host='0.0.0.0', port=5000, debug=False)
